package grdnlog.service;

import grdnlog.bean.GardenLogConfig;
import grdnlog.bean.GardenLogEntry;
import grdnlog.dao.GardenLogConfigDao;
import grdnlog.dao.GardenLogEntryDao;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.util.StringUtils;

public class GardenLogService {

	private static final String HASHTAG = "#grdnlog";
	
	private TwitterTemplate twitter = new TwitterTemplate();
	private TwitterHelper helper = new TwitterHelper();
	
	@Autowired
	private GardenLogEntryDao gardenLogEntryDao;
	
	@Autowired
	private GardenLogConfigDao gardenLogConfigDao;
	
	public List<GardenLogEntry> getGardenLogEntries(String userId) {
		return gardenLogEntryDao.get(userId);
	}
	
	public List<GardenLogEntry> getGardenLogEntries(String userId, Date fromDate, Date toDate) {
		return gardenLogEntryDao.get(userId, fromDate, toDate);
	}
	
	public List<GardenLogConfig> getGardenLogConfigs(String userId) {
		return gardenLogConfigDao.getAll(userId);
	}
	
	public void saveGardenLogConfig(GardenLogConfig config) {
		if (StringUtils.hasText(config.getId())) {
			gardenLogConfigDao.update(config);
		} else {
			gardenLogConfigDao.create(config);
		}
	}
	
	public void deleteGardenLogConfig(String id, String userId) {
		gardenLogConfigDao.deleteById(id);
	}
	
	public void deleteGardenLogEntry(String id, String userId) {
		gardenLogEntryDao.deleteById(id);
	}
	
	public void syncGardenLogEntries(String userId) {
		for (GardenLogConfig config : gardenLogConfigDao.getAll(userId)) {
						
			final List<Tweet> results;
			
			if (StringUtils.hasText(config.getLastTweet())) {
				results = helper.getUserTimeline(twitter, config.getTwitterName(), 5000, config.getLastTweet());
			} else {
				results = helper.getUserTimeline(twitter, config.getTwitterName(), 5000);
			}
			
			boolean first = true;
			
			for(Tweet tweet : results) {
				if (first) {
					config.setLastTweet(String.valueOf(tweet.getId()));
					gardenLogConfigDao.update(config);
					first = false;
				}
				
				if (!config.getTaggedOnly() || tweet.getText().contains(HASHTAG)) {
					GardenLogEntry entry = new GardenLogEntry();
					entry.setTweetId(String.valueOf(tweet.getId()));
					entry.setText(tweet.getText().replace(HASHTAG, "").trim());
					entry.setDate(tweet.getCreatedAt());
					entry.setUserId(userId);
					gardenLogEntryDao.create(entry);
				}
			}
		}
	}
	
}
